class ApplicationController < ActionController::Base
  #protect_from_forgery

  before_filter :require_login

  def require_login
    if is_guest
      flash[:message] = 'You must login first'
      redirect_to :controller => 'user', :action => 'login', :method => :get
    end
  end

  def is_guest
    if !session[:user].is_a?(User)
      return true
    elsif session[:user].username == 'guest'
      return true
    else
      return false
    end
  end

  def get_cart
    if session[:cart_id] == nil
      Cart.destroy_all
      LineItem.destroy_all
      cart = Cart.new
      session[:cart_id] = cart.id
    else
      cart = Cart.find(session[:cart_id])
    end

    return cart
  end

  def get_user(id = nil)
    if id == nil && is_guest
      user = User.find_by_username('guest')
      session[:user] = user
    elsif id == session[:user].id
      user = session[:user]
    else
      user = User.find(id)
    end

    return user
  end

  def create_user_session(user)
    if is_guest
      session[:user] = user
    else
      flash[:message] = 'You must logout first!'
    end
  end

  def destroy_user_session
    session[:user] = nil
  end
end
